

var mysql = require("mysql");
const dbPool = mysql.createPool({
    database: "cyue_share",
    user: "root",
    password: "weifei"
});



BigInt.prototype.toJSON = function () { return this.toString() };


module.exports = {

	/**
	 * @returns { mariadb.Pool }
	 */
	getPool() {
		return dbPool;
	},


	/**
	 * 
	 * @param { string | mysql.QueryOptions } sql 
	 * @param { any[] } values 
	 * @returns { Promise<any[]> }
	 */
	query(sql, values)
	{
		return new Promise((resolve, reject) => {
			const queryCallback = (err, results, _fields) => {
				if (err)
					reject(err);
				resolve(results);
			}

			if (!values)
			{
				dbPool.query(
					sql,
					queryCallback
				);
			}
			else
			{
				dbPool.query(
					sql,
					values,
					queryCallback
				);
			}

		});
	},


	/**
	 * @returns { Promise<mysql.Connection> }
	 */
	createConnection() {
		return mysql.createConnection({
			database: "cyue_share",
			user: "root",
			password: "weifei"
		})
	},


	/**
	 * @returns { Promise<PoolConnection> }
	 */
	getConnection() {
		return dbPool.getConnection();
	},


	/**
	 * 
	 * @param { string[] } sqlArray
	 * @param { any[][] } paramArray
	 * @returns { Promise<object[][]> }
	 */
	transactionQuery(sqlArray, paramArray) {
		return new Promise((resolve, reject) => {
			dbPool.getConnection((err, connection) => {
				if (err)
				{
					console.error(err);
					reject(err);
				}

				connection.beginTransaction(err => {
					if (err)
					{
						console.error(err);
						reject(err);
					}


					const promiseArray = new Array(sqlArray,length);
					for (let i = 0; i < sqlArray.length; i++) {
						const sql = sqlArray[i];
						const param = paramArray[i];

						promiseArray[i] = new Promise((resolve, reject) => {
							connection.query(sql, param, (err, result) => {
								if (err)
								{
									console.error(err);
									reject(err);
								}
								resolve(result);
							});
						})
					}


					Promise.all(promiseArray)
					.then(resultArray => {
						connection.commit(commitError => {
							if (commitError)
							{
								console.error(commitError);
								connection.rollback(err => {
									connection.release();
									if (err)
									{
										console.error(err);
										reject(err);
									}
									reject(commitError);
								});
								return;
							}
	
							connection.release();
							resolve(resultArray);
						});
					})
					.catch(err => {
						connection.release();
						reject(err);
					})

					
				});
			});
		})
		
	}
}




